package com.zjitc.service.imp;

import com.zjitc.common.Gsonal;
import com.zjitc.common.PageModel;
import com.zjitc.common.ServerResponse;
import com.zjitc.common.redis.RedisCache;
import com.zjitc.dao.UserDao;
import com.zjitc.pojo.User;
import com.zjitc.service.UserService;
import com.zjitc.utils.Mail;
import com.zjitc.utils.RedisAuto;
import com.zjitc.utils.Utils;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Objects;
import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Create By IntelliJ IDEA
 *
 * @author:
 * @create-Time: 2017/11/7  15:56
 */
@Service
public class UserServiceImpl implements UserService {

  @Autowired
  private UserDao dao;

  @Autowired
  private RedisCache redis;

  private static final String USERS = "users";
  private static final String USER = "user";
  private final String MSG = "msg";

  @Override
  public boolean regiser(User user, String path) {
    if (dao.findbyusername(user.getUsername()) != null) {
      return false;
    }
    int success = dao.add(user);
    if (success == 1) {
      //更新缓存
      RedisAuto.usersredis(dao, redis, USERS);

      Mail mail = new Mail();
      String url = "";
      url =
          "http://localhost:8080" + path + "/user/active.do?uid=" + user.getUid() + "&code=" + user
              .getCode();
      StringBuilder builder = new StringBuilder(1024);
      builder.append("<h3>").append("激活邮件，点击以下链接进行账号激活").append("</h3>");
      builder.append("<a href='").append(url).append("'>").append(url).append("</a>");
      try {
        mail.send(user.getEmail(), "激活邮件", builder.toString());
      } catch (MessagingException e) {
        throw new RuntimeException(e);
      }
    }
    return true;
  }

  @Override
  public boolean active(String uid, String code) {

    User user = dao.findbyid(uid);
    if (code.equals(user.getCode())) {
      user.setState(1);
      dao.update(user);
      RedisAuto.usersredis(dao, redis, USERS);
      return true;
    }
    return false;
  }

  @Override
  public ServerResponse<User> login(String username, String password, String verification,
      HttpSession session) throws UnsupportedEncodingException, NoSuchAlgorithmException {
      checkredis();
      String msg = String.valueOf(session.getAttribute(MSG));
      if (msg.equalsIgnoreCase(verification)) {

      password = Utils.encoderByMd5(password);
      String json = redis.hashMapget(USERS, username);
      User user = Gsonal.fromJson(json, User.class);
      if (user != null) {
        if (user.getState() != -1) {
          if (user.getPassword().equals(password)) {
            session.setAttribute(USER, user);
            return ServerResponse.createSuccess("1");
          }
          return ServerResponse.createSuccess("-1");
        }
        return ServerResponse.createSuccess("-2");
      }
      return ServerResponse.createSuccess("-1");
    }
    return ServerResponse.createSuccess("0");

  }

  @Override
  public ServerResponse<User> checkUsername(String username) {
    if (!redis.exists(USERS)) {
      RedisAuto.usersredis(dao, redis, USERS);
    }
    String tojson = redis.hashMapget(USERS, username);
    if (tojson != null) {
      return ServerResponse.createSuccess("0");
    }
    return ServerResponse.createSuccess("1");

  }

  @Override
  public PageModel<User> findall(int pageid, int count) {
    List<User> users = redis.hashListGetAll(USERS, User.class);
    PageModel<User> pageModel = new PageModel<>(users, count, pageid);
    return pageModel;
  }

  @Override
  public void update(User user) {
    dao.update(user);
    RedisAuto.usersredis(dao, redis, USERS);
  }

  @Override
  public User findbyuid(String uid) {
    return dao.findbyid(uid);
  }

  @Override
  public void deluser(String uid) {
    dao.deluser(uid);
    RedisAuto.usersredis(dao, redis, USERS);
  }

  @Override
  public ServerResponse checkpassword(String password, String verifypassword) {
    if (password != null) {
      if (password.equals(verifypassword)) {
        return ServerResponse.createSuccess("1");
      } else {
        return ServerResponse.createSuccess("0");
      }
    }
    return ServerResponse.createSuccess("0");
  }

  @Override
  public User adminLogin(String username, String password) {
    Integer hundred = 100;
    checkredis();
    String json = redis.hashMapget(USERS, username);
    User user = Gsonal.fromJson(json, User.class);
    try {
      if (user.getPassword().equals(Utils.encoderByMd5(password))) {
        if (Objects.equals(user.getState(), hundred)) {
          return user;
        }
      }
      return null;
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
      e.printStackTrace();
      return null;
    }
  }

  private void checkredis() {
      if (!redis.exists(USERS)) {
        RedisAuto.usersredis(dao, redis, USERS);
      }
  }
}
